
<template>
  <div :style="{ backgroundImage: `url(${require('@/assets/0034034892281415_b.jpg')})`,
   backgroundSize: 'cover', display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh',overflow: 'hidden'}">
    <el-card class="box-card">
      <h2>注册</h2>
      <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-position="left"
          label-width="80px"
          class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="uname">
          <el-input v-model="ruleForm.uname"></el-input>
        </el-form-item>
        <el-form-item label="email" prop="email" >
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="ruleForm.age"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="ruleForm.gender" size="small">
            <el-radio-button label="男">男</el-radio-button>
            <el-radio-button label="女">女</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              type="password"
              v-model="ruleForm.pass"
              autocomplete="off"
              :rules="rules.pass"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password">
          <el-input
              type="password"
              v-model="ruleForm.password"
              autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="btnGroup">
        <el-button type="primary" @click="submitForm('ruleForm')"
        >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>
  </div>
</template>



<script>
import axios from "axios";

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    const validateNumber = (rule, value, callback) => {
      const reg = /^\d+$/; // 定义正则表达式，匹配一个或多个数字字符
      if (!reg.test(value)) { // 如果验证不通过
        callback(new Error('请输入数字')); // 抛出错误提示信息
      } else if (value < 0 || value > 100) { // 如果超出取值范围
        callback(new Error('请输入0-100之间的数字')); // 抛出错误提示信息
      } else { // 如果验证通过
        callback(); // 不抛出任何异常
      }
    };


    return {
      ruleForm: {
        uname: "",
        password: "",
        pass: "",
        email: '',
        age: '',
        gender: '',
      },
      rules: {
        uname: [
          { required: true, message: "用户名不能为空！", trigger: ['blur', 'change'] },
        ],
        pass: [{ required: true, validator: validatePass, trigger: ['blur', 'change'] },
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/,
            message: '密码必须包含大写字母、小写字母和数字，并且至少8个字符',
            trigger: ['blur', 'change']
          }],
        password: [
          { required: true, validator: validatePass2, trigger: ['blur', 'change'] },
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        age: [
          { required: true, validator: validateNumber, trigger: ['blur','change'] },

        ],

      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let _this = this;
          // 构建发送到后端的数据
          axios({
            url: "/api/user/register",               // 请求地址
            method: "post",                       // 请求方法
            headers: {                            // 请求头
              "Content-Type": "application/json",
            },
            params: {                             // 请求参数
              uname: _this.ruleForm.uname,
              password: _this.ruleForm.password,
              email: _this.ruleForm.email,
              age: _this.ruleForm.age,
              gender: _this.ruleForm.gender
            },
            // 发送POST请求到后端
          })
              .then((res) => {
                if (res.data.code === "0") {  // 当响应的编码为 0 时，说明登录成功
                  // 将用户信息存储到sessionStorage中
                  sessionStorage.setItem("userInfo", JSON.stringify(res.data.data));
                  alert("注册成功！您的id是：  "+res.data.data.uid
                      +"  将返回登陆页面,");
                  // 跳转页面到首页
                  this.$router.push('/login');
                  // 显示后端响应的成功信息
                }else {
                  alert(res.data.msg)
                  console.log("error submit!!");
                  return false;
                }
              })}
      })
    },
    resetForm(formName){
      this.$refs[formName].resetFields();
    },
    goBack() {
      this.$router.go(-1);
    },

  },
};

</script>

<style scoped>
.box-card {
  margin: auto auto;
  width: 400px;
}
</style>
